package com.rlyy.rsj.job.remind;

import com.rlyy.aibase.utils.base.TableNode;
import com.rlyy.rsj.common.JobConstans;
import com.rlyy.rsj.common.RemindType;
import com.rlyy.rsj.dao.OrgpDao2;
import com.rlyy.rsj.entity.ReceiveUser;
import com.rlyy.rsj.entity.RemindEntity;
import com.rlyy.rsj.entity.RemindTable;
import com.rlyy.rsj.entity.UsageRemindEntity;
import com.rlyy.rsj.job.IScheduler;
import com.rlyy.rsj.service.remind.IRemindService;
import com.rlyy.rsj.service.user.IUserService;
import com.rlyy.rsj.utils.DistributeLock;
import com.rlyy.rsj.utils.JSONUtils;
import com.rlyy.rsj.utils.RedisKeyFactory;
import com.rlyy.rsj.utils.RedisUtils;
import common.util.DateTimeFormatterUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.rlyy.rsj.utils.DistributeLock.oneMinute;

/**
 * @author : shibixiao
 * @description :
 * @date : 2021-07-21 14:32
 **/
@Component
public class DoRemindJob implements IScheduler {

    Logger logger = LoggerFactory.getLogger(DoRemindJob.class);

    private static final String LOCK_KEY = RedisKeyFactory.wrapJobKey(DoRemindJob.class.getName());
    private static final String REMIND_KEY = RedisKeyFactory.wrapJobKey("remind");
    private static final String HEALTH_KEY = RedisKeyFactory.wrapJobKey("remind_health");

    @Autowired
    private IRemindService remindService;

    @Autowired
    private List<IRemind> iReminds;

    @Autowired
    private IUserService userService;

    @Override
    @Scheduled(cron = "0 30 9 * * ?")
    public void scheduler() {
        try {
            boolean lock = DistributeLock.lock(LOCK_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), oneMinute);
            if (lock) {
                logger.info("{}-开始定时任务:{}",LOCAL_INFO, "预警任务");
                //统计存活状态
                RedisUtils.hset(HEALTH_KEY, LOCAL_INFO, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()));

                List<RemindEntity> reminds = remindService.getAllOrgpInfo();
                //获取预警信息
                for (IRemind iRemind : iReminds){
                    RemindTable remindConfigByType = remindService.getRemindConfigByType(iRemind.getRemindType().getCode());
                    if(Objects.isNull(remindConfigByType)){
                        continue;
                    }
                    String receiveUserId = remindConfigByType.getReceiveUserId();
                    if(StringUtils.isBlank(receiveUserId)){
                        logger.warn("{}-未获取到接收人", RemindType.getInfoByCode(remindConfigByType.getRemindType()));
                        continue;
                    }
                    String[] users = receiveUserId.split(",");
                    List<ReceiveUser> receiveUserList = Arrays.stream(users).map(userId -> userService.getReceiveUserById(userId)).filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    for (RemindEntity remindEntity : reminds){
                        if(iRemind.remindCondition(remindEntity, remindConfigByType)){
                            receiveUserList.forEach(receiveUser -> iRemind.doRemind(remindEntity,receiveUser));
                        }
                    }
                }

                //统计完成状态
                RedisUtils.set(REMIND_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), -1);
                DistributeLock.unlock(LOCK_KEY);
            } else {
                logger.warn("{}-未执行预警任务!",LOCAL_INFO);
            }

        } catch (Exception e) {
            logger.error("{}-合同预警任务执行失败!",LOCAL_INFO, e);
            throw new RuntimeException("合同预警任务执行失败!", e);
        }
    }

}
